<template>
  <div class="order-confirm">
    <div class="container">
      <el-breadcrumb separator="/" class="breadcrumb">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/cart' }">购物车</el-breadcrumb-item>
        <el-breadcrumb-item>确认订单</el-breadcrumb-item>
      </el-breadcrumb>

      <el-card class="confirm-card">
        <template #header>
          <span>确认订单信息</span>
        </template>

        <!-- 收货信息 -->
        <el-form :model="form" :rules="rules" ref="formRef" label-width="90px" class="receiver-form">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="收货人" prop="receiverName">
                <el-input v-model="form.receiverName" placeholder="请输入收货人姓名" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="手机号" prop="receiverPhone">
                <el-input v-model="form.receiverPhone" placeholder="请输入手机号" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="收货地址" prop="receiverAddress">
                <el-input v-model="form.receiverAddress" placeholder="请输入收货地址" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

        <!-- 商品列表 -->
        <div class="order-items">
          <el-table :data="cartItems" border stripe>
            <el-table-column prop="productName" label="商品名称" />
            <el-table-column prop="productPrice" label="单价" width="100">
              <template #default="scope">
                ¥{{ scope.row.productPrice }}
              </template>
            </el-table-column>
            <el-table-column prop="quantity" label="数量" width="80" />
            <el-table-column prop="subtotal" label="小计" width="100">
              <template #default="scope">
                ¥{{ (scope.row.productPrice * scope.row.quantity).toFixed(2) }}
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 订单总价 -->
        <div class="order-total">
          <span>订单总价：</span>
          <span class="total-price">¥{{ totalPrice.toFixed(2) }}</span>
        </div>

        <!-- 提交按钮 -->
        <div class="order-actions">
          <el-button type="primary" size="large" :loading="submitting" @click="submitOrder">
            提交订单
          </el-button>
          <el-button @click="$router.push('/cart')">返回购物车</el-button>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { useCartStore } from '@/stores/cart'
import { createOrder } from '@/api/order'

const router = useRouter()
const userStore = useUserStore()
const cartStore = useCartStore()

const cartItems = computed(() => cartStore.cartItems)
const totalPrice = computed(() => cartStore.totalPrice)

const formRef = ref()
const submitting = ref(false)

const form = ref({
  receiverName: userStore.userInfo?.nickname || '',
  receiverPhone: userStore.userInfo?.phone || '',
  receiverAddress: '',
})

const rules = {
  receiverName: [{ required: true, message: '请输入收货人', trigger: 'blur' }],
  receiverPhone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
  receiverAddress: [{ required: true, message: '请输入收货地址', trigger: 'blur' }]
}

const submitOrder = async () => {
  if (!formRef.value) return
  if (cartItems.value.length === 0) {
    ElMessage.warning('购物车为空，无法下单')
    router.push('/cart')
    return
  }
  try {
    await formRef.value.validate()
    submitting.value = true
    // 组装订单数据
    const orderData = {
      userId: userStore.userInfo.id,
      receiverName: form.value.receiverName,
      receiverPhone: form.value.receiverPhone,
      receiverAddress: form.value.receiverAddress,
      totalPrice: totalPrice.value,
      items: cartItems.value.map(item => ({
        productId: item.productId,
        productName: item.productName,
        productImg: item.productImage,
        productPrice: item.productPrice,
        quantity: item.quantity,
        subtotal: (item.productPrice * item.quantity)
      }))
    }
    const response = await createOrder(orderData)
    if (response.data) {
      ElMessage.success('下单成功！')
      // 清空购物车
      await cartStore.clearAllItems()
      // 跳转到下单成功页
      router.replace(`/order/success/${response.data.id}`)
    }
  } catch (error) {
    console.error('下单失败:', error)
    ElMessage.error(error.message || '下单失败')
  } finally {
    submitting.value = false
  }
}
</script>

<style scoped>
.order-confirm {
  padding: 20px 0;
}
.container {
  max-width: 900px;
  margin: 0 auto;
  padding: 0 20px;
}
.breadcrumb {
  margin-bottom: 30px;
}
.confirm-card {
  padding: 30px 20px;
}
.receiver-form {
  margin-bottom: 30px;
}
.order-items {
  margin-bottom: 20px;
}
.order-total {
  text-align: right;
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 20px;
}
.total-price {
  color: #e74c3c;
  font-size: 22px;
}
.order-actions {
  text-align: right;
  margin-top: 20px;
}
</style> 